#include "can.h"
#include "dri_can.h"
#include "string.h"
#include "mp.h"


can_receive_message_struct RxMessage;

void app_can_init(uint16_t rate);

void bms_ver_info_fun(can_receive_message_struct *version);

void can_analyze(void);

//typedef struct
//{
//	uint
//}
typedef void (*callback_fx)(can_receive_message_struct *rx_data);

uint8_t top=0;

uint8_t rear=0;

can_receive_message_struct  rx_queue[50]={0};

typedef struct
{
	uint32_t extid;
	uint8_t recbuff[8];
}recive_struct;
recive_struct version_info;

//typedef struct
//{
//	uint8_t can_id;
//	bool tx_single;
//	can_callback_fun rx_callback;
//}can_list_struct;
//can_list_struct can_list[]=
//{
//	CAN0_ID,FALSE,
//}

typedef struct
{
	uint32_t fun_id;
	callback_fx callback_function;
}fun_id_struct;

fun_id_struct funID_list[20]=
{
	{0x01000FFA,bms_ver_info_fun},
	{0x01001FFA,bms_factory_info_fun},
	{0x01002FFA,bms_output_day_fun},
	{0x01003FFA,bms_SN_code_fun},
	{0x01004FFA,bms_para_fun},
	{0x1010FFA7,bms_workstatus_fun},
	{0x1011FFA7,general_battery_info_fun},
	{0x1012FFA7,bms_SOP_info_fun},
	{0x01020FFA,bms_vol_MOS_fun},
	{0x01021FFA,bms_moment_cur_fun},
	{0x01022FFA,bms_insulation_info_fun},
	{0x01023FFA,bms_SOX_info_fun},
	{0x01024FFA,bms_left_info_fun},
	{0x01025FFA,bms_single_info_fun},
	{0x01026FFA,bms_con_cur_info_fun},
	{0x01027FFA,bms_temp_info_fun},
	{0x01028FFA,bms_error_info_fun},
	{0x01030FFA,bms_vol_info_fun},
	{0x01031FFA,bms_singletemp_info_fun},
	{0x01032FFA,bms_realtime_info_fun}	
};

void app_can_init(uint16_t rate)
{
	dri_can0_init(rate);
//	callback_list[can_id].rx_callback=rx_callback;
//	callback_list[can_id].tx_single=single;
}

//void can_analyze(void)
//{
//	can_receive_message_struct RxMessage;
//	
//}
void app_fill_rx_queue(can_receive_message_struct rx_fill_queue)
{
	rx_queue[rear]=rx_fill_queue;
	rear++;
	if(rear==50)
	{
		rear=0;
	}

}

bool app_queue_item_get(can_receive_message_struct *Rx)
{
	if(top==rear)
	{
		return FALSE;
	}
	else
	{
		*Rx=rx_queue[top];
		memset(&rx_queue[top],0,sizeof(can_receive_message_struct));
		top++;
		return TRUE;
	}
}

void can_analyze(void)
{
	
	if(app_queue_item_get(&RxMessage))
	{
			if((RxMessage.rx_efid>>16==0x1010)||(RxMessage.rx_efid>>16==0x1011)||(RxMessage.rx_efid>>16==0x1012))
		{
			switch(RxMessage.rx_efid)
			{	
			case 0x1010FFA7:
				bms_workstatus_fun(&RxMessage);
				break;
			
			case 0x1011FFA7:
				general_battery_info_fun(&RxMessage);
				break;
			
			case 0x1012FFA7:
				bms_SOP_info_fun(&RxMessage);
				break;
			}
		}
		else
		{
			for(int i=0;i<20;i++)
			{
				if(funID_list[i].fun_id==RxMessage.rx_efid)
				funID_list[i].callback_function(&RxMessage);
			}
		}
	}
	
	
}

void CAN0_RX0_IRQHandler(void)
{
	can_receive_message_struct can_rx;
	if(CAN_RFIFO0(CAN0) & 0x03)
	{
		can_message_receive(CAN0,CAN_FIFO0,&can_rx);
	}
	
}
